package com.luyue.zagj.activity.home;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luyue.zagj.BaseActivity;
import com.luyue.zagj.MainActivity;
import com.luyue.zagj.R;
import com.luyue.zagj.activity.myAccount.CarInfoActivity;
import com.luyue.zagj.address.City;
import com.luyue.zagj.address.CityPickerDialog;
import com.luyue.zagj.address.County;
import com.luyue.zagj.address.Util;
import com.luyue.zagj.domin.PeopleInfomation;
import com.luyue.zagj.domin.Province;
import com.luyue.zagj.utils.CharacterFormatUtil;

import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.functions.Action1;


public class ApplyLabelActivity extends BaseActivity {

    private static final int REQUEST_IMAGE = 3;
    @Bind(R.id.apply_label_cancel_btn)  //返回键
            Button applyLabelCancelBtn;
    @Bind(R.id.apply_label_top_rl)
    RelativeLayout applyLabelTopRl;
    @Bind(R.id.apply_label_name_ed)   //名字
            EditText applyLabelNameEd;
    @Bind(R.id.apply_label_idcard_ed) //身份证
            EditText applyLabelIdcardEd;
    @Bind(R.id.apply_label_phone_ed)  //手机号
            EditText applyLabelPhoneEd;
    @Bind(R.id.apply_label_household_ed)  //户籍
            TextView applyLabelHouseholdEd;
    @Bind(R.id.apply_label_home_address)  //户籍选择
            ImageView applyLabelHomeAddress;
    /*@Bind(R.id.apply_label_household_detail_ed) //户籍详细
            EditText applyLabelHouseholdDetailEd;*/
    @Bind(R.id.apply_label_address_ed)   //现住址
            EditText applyLabelAddressEd;
    @Bind(R.id.apply_label_loc_address)   //现住址选择
            ImageView applyLabelLocAddress;
    /*@Bind(R.id.apply_label_address_detail_ed) //现住址详细
            EditText applyLabelAddressDetailEd;*/
    @Bind(R.id.apply_label_invoice_y_rb)    //有发票
            RadioButton applyLabelInvoiceYRb;
    @Bind(R.id.apply_label_invoice_n_rb)    //无发票
            RadioButton applyLabelInvoiceNRb;
    @Bind(R.id.apply_label_invoice_rg)     // 发票RadioGroup
            RadioGroup applyLabelInvoiceRg;
    /*@Bind(R.id.apply_label_brand_sp)    //品牌 选择
            Spinner applyLabelBrandSp;*/
    @Bind(R.id.apply_label_chassis_ed)     //车架号
            EditText applyLabelChassisEd;
    @Bind(R.id.apply_label_motor_ed)       //电机号
            EditText applyLabelMotorEd;
    @Bind(R.id.apply_label_color_ed)     //颜色
            EditText applyLabelColorEd;
    @Bind(R.id.apply_label_buy_time_ed)     //购买时间
            TextView applyLabelBuyTimeEd;
    @Bind(R.id.apply_label_date_picker)     //购买时间 选择
            ImageView applyLabelDatePicker;
    @Bind(R.id.apply_label_sure_tv)    //申请按钮
            TextView applyLabelSureTv;
    /* @Bind(R.id.apply_label_brand_sp)
     Spinner applyLabelBrandSp;*/
    @Bind(R.id.tv_price)
    TextView tv_price;
    @Bind(R.id.ll_buytime)
    LinearLayout ll_buytime;
    @Bind(R.id.tv_appiontment)
    TextView tvappiontment;
    @Bind(R.id.select_iv_idcardposition1)
    ImageView selectIvIdcardposition1;
   /* @Bind(R.id.select_iv_idcardback1)
    ImageView selectIvIdcardback1;
    @Bind(R.id.select_iv_carinfo1)
    ImageView selectIvCarinfo1;
    @Bind(R.id.select_arrmedphoto1)
    ImageView selectArrmedphoto1;
    @Bind(R.id.select_call_police1)
    ImageView selectCallPolice1;
    @Bind(R.id.select_home_insurance1)
    ImageView selectHomeInsurance1;*/
    @Bind(R.id.activity_select_image)
    LinearLayout activitySelectImage;
    @Bind(R.id.tv_appiontment_location)
    TextView tvAppiontmentLocation;


    private List<String> list;      //品牌 数组
    private ArrayAdapter adpter;

    /**
     * 当前的年月日
     * year,monthOfYear,dayOfMonth
     */
    private Calendar calendar;
    private int year;
    private int monthOfYear;
    private int dayOfMonth;
    private String provinceId;

    /**
     * 判断是户籍还是现住址  0 户籍  1现住址
     * year,monthOfYear,dayOfMonth
     */
    private int addressType;
    String s1, s2, s3;   //省市县

    private ArrayList<Province> provinces = new ArrayList<Province>();

    /**
     * EditText RadioButton Spinner 取值
     */
    private String name;  //
    private String idcard;
    private String phone;
    private String household;
    private String household_detail;
    private String address;
    private String address_detail;

    private boolean invoice;  //有无发票
    private String brand;
    private String chassis;
    private String motor;
    private String color;
    private String buy_time;
    private SharedPreferences sp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_label);
        ButterKnife.bind(this);
        sp = getSharedPreferences("config", MODE_PRIVATE);
        getSavaedState();
        initData();

    }


    private void initData() {
        //日期数据初始
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        monthOfYear = calendar.get(Calendar.MONTH);
        dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        imageViews.add(selectIvIdcardposition1);
       /* imageViews.add(selectIvIdcardback1);
        imageViews.add(selectIvCarinfo1);
        imageViews.add(selectArrmedphoto1);
        imageViews.add(selectCallPolice1);
        imageViews.add(selectHomeInsurance1);*/
    }

    private ArrayList<String> createArrays(String name) {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add(name + i);
        }
        return list;
    }

    /**
     * 各控件点击事件
     */
    @OnClick({R.id.apply_label_cancel_btn, R.id.apply_label_sure_tv,
            R.id.apply_label_date_picker, R.id.apply_label_home_address,
            R.id.apply_label_loc_address, R.id.apply_label_buy_time_ed,
            R.id.apply_label_household_ed, R.id.apply_label_invoice_n_rb,
            R.id.tv_appiontment, R.id.activity_select_image,
            R.id.tv_appiontment_location,R.id.tv_price,
            })
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.apply_label_cancel_btn:
                this.finish();
                break;
            case R.id.apply_label_home_address:
                addressType = 0;
                setAddress();
                break;
            case R.id.apply_label_household_ed:
                addressType = 0;
                setAddress();
                break;
            case R.id.apply_label_loc_address:
                addressType = 1;
                setAddress();
                break;
            case R.id.apply_label_date_picker:
            case R.id.apply_label_buy_time_ed:
                openDatePicker();
                break;
            case R.id.apply_label_sure_tv:
                CheckSure();
                break;
            case R.id.apply_label_invoice_n_rb:
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                // 设置参数
                alertDialog.setTitle("承诺书").setIcon(R.mipmap.ic_launcher)
                        .setMessage(Html.fromHtml("&nbsp 本人承诺：申请安装标签的" + "<font color=red>艾玛</font>" +
                                "品牌电动自行车&nbsp <br/>系本人<br/>（姓名" + "<font color=red>大苏打</font>" +
                                "身份号" + "<font color=red>31323123132</font>" +
                                "    ）</br>合法所有，该车的购车发票及车辆出厂合格证由于本人保管不善而遗失。<br/>以上情况如有不符，本人愿意承担相应的法律责任！"))
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {// 积极

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(ApplyLabelActivity.this, "已确认", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }).setNegativeButton("取消", null);
                alertDialog.create().show();
                break;
            case R.id.tv_price:
                showDialog("艾玛", "选择品牌", tv_price);
                break;
            case R.id.tv_appiontment:
                showDialog("2016/11/", "选择日期", tvappiontment);
                break;
            case R.id.activity_select_image:
                Intent intent = new Intent(this, CarInfoActivity.class);
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
            case R.id.tv_appiontment_location:
                showDialog("滨江区南环路100","选择预约地点",tvAppiontmentLocation);
                break;
         }
    }


    private ArrayList<File> files;
    private List<ImageView> imageViews = new ArrayList();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_IMAGE:
                if (data == null) {
                    return;
                }
                PeopleInfomation people = (PeopleInfomation) data.getSerializableExtra("people");
                files = people.files;
                if (files.get(5).length()>0) {
                    Glide.with(this).load(files.get(5)).into(imageViews.get(0));
                }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getSavaedState();
    }

    private void getSavaedState() {
        Log.i("状态", "ThirdActivity onSaveInstanceState");
        applyLabelNameEd.setText(sp.getString("name", ""));
        applyLabelIdcardEd.setText(sp.getString("idcard", ""));
        applyLabelPhoneEd.setText(sp.getString("phone", ""));
        applyLabelHouseholdEd.setText(sp.getString("household", ""));
        applyLabelAddressEd.setText(sp.getString("address", ""));
        boolean isInvoice = sp.getBoolean("applyLabelInvoiceYRb", true);
        if (isInvoice) {
            applyLabelInvoiceYRb.setChecked(false);
            applyLabelInvoiceNRb.setChecked(true);
        } else {
            applyLabelInvoiceYRb.setChecked(true);
            applyLabelInvoiceNRb.setChecked(false);
        }

    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.i("状态", "ThirdActivity onSaveInstanceState");
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("name", applyLabelNameEd.getText().toString());
        edit.putString("idcard", applyLabelIdcardEd.getText().toString());
        edit.putString("phone", applyLabelPhoneEd.getText().toString());
        edit.putString("household", applyLabelHouseholdEd.getText().toString());
        edit.putString("address", applyLabelAddressEd.getText().toString());
        edit.putBoolean("applyLabelInvoiceYRb", invoice);
        edit.commit();
        super.onSaveInstanceState(outState);

    }

    private void showDialog(String name, String type, final TextView view) {
        final ArrayList<String> lists = createArrays(name);
        final String[] datas = new String[lists.size()];
        lists.toArray(datas);
        AlertDialog.Builder builder = new AlertDialog.Builder(ApplyLabelActivity.this);
        builder.setTitle(type); //设置标题
        //builder.setMessage("是否确认退出?"); //设置内容
        builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
        //设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。
        builder.setItems(datas, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                view.setText(datas[which]);
                dialog.dismiss();
                Toast.makeText(ApplyLabelActivity.this, datas[which], Toast.LENGTH_SHORT).show();

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                view.setText(datas[0]);
                dialog.dismiss();
                Toast.makeText(ApplyLabelActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }

    private void CheckSure() {
        name = applyLabelNameEd.getText().toString();
        idcard = applyLabelIdcardEd.getText().toString();
        phone = applyLabelPhoneEd.getText().toString();
        household = applyLabelHouseholdEd.getText().toString();
        address = applyLabelAddressEd.getText().toString();
       /* household_detail = applyLabelHouseholdDetailEd.getText().toString();
        address_detail = applyLabelAddressDetailEd.getText().toString();*/
        if (applyLabelInvoiceYRb.isChecked()) {
            invoice = true;
        } else {
            invoice = false;
        }
        //brand = applyLabelBrandSp.getSelectedItem().toString();
        brand = tv_price.getText().toString().trim();
        chassis = applyLabelChassisEd.getText().toString();
        motor = applyLabelMotorEd.getText().toString();
        color = applyLabelColorEd.getText().toString();
        buy_time = applyLabelBuyTimeEd.getText().toString();

        if (null == name || "".equals(name)) {
            Toast.makeText(this, "名字不能为空", Toast.LENGTH_SHORT).show();
        } else if (null == idcard || "".equals(idcard)) {
            Toast.makeText(this, "身份证不能为空", Toast.LENGTH_SHORT).show();
        } else if (!CharacterFormatUtil.isPersonIdValid(idcard)) {
            Toast.makeText(this, "身份证格式不正确", Toast.LENGTH_SHORT).show();
        } else if (null == phone || "".equals(phone)) {
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
        } else if (!CharacterFormatUtil.isPhoneNumberValid(phone)) {
            Toast.makeText(this, "手机号格式不正确", Toast.LENGTH_SHORT).show();
        } else if (null == household || "".equals(household)) {
            Toast.makeText(this, "请选择户籍地址", Toast.LENGTH_SHORT).show();
        } else if (null == household_detail || "".equals(household_detail)) {
            Toast.makeText(this, "请输入户籍详细", Toast.LENGTH_SHORT).show();
        } /*else if (null == address || "".equals(address)) {
            Toast.makeText(this, "请选择现居地地址", Toast.LENGTH_SHORT).show();
        } else if (null == address_detail || "".equals(address_detail)) {
            Toast.makeText(this, "请输入现居地详细", Toast.LENGTH_SHORT).show();
        }*/ else if ("请选择品牌".equals(brand)) {
            Toast.makeText(this, "请选择车辆品牌", Toast.LENGTH_SHORT).show();
        } else if (null == chassis || "".equals(chassis)) {
            Toast.makeText(this, "车架号不能为空", Toast.LENGTH_SHORT).show();
        } else if (null == motor || "".equals(motor)) {
            Toast.makeText(this, "电动机号不能为空", Toast.LENGTH_SHORT).show();
        } else if (null == color || "".equals(color)) {
            Toast.makeText(this, "请描述车辆颜色", Toast.LENGTH_SHORT).show();
        } else if (null == color || "".equals(color)) {
            Toast.makeText(this, "请选择车辆购买时间", Toast.LENGTH_SHORT).show();
        } else {
            //调用接口 传递数据
            //完成后跳转
            //模拟跳转
            Intent it = new Intent(this, MainActivity.class);
            startActivity(it);
            finish();
            Toast.makeText(this, "申请成功", Toast.LENGTH_SHORT).show();
        }


    }

    /**
     * 户籍及现居住选择时事件
     */
    private void setAddress() {
        if (provinces.size() > 0) {
            showAddressDialog();
        } else {
            new InitAreaTask(ApplyLabelActivity.this).execute(0);
        }
    }

    /**
     * 户籍及现居住选择时事件   打开Dialog
     */
    private void showAddressDialog() {
        new CityPickerDialog(ApplyLabelActivity.this, provinces, null, null, null,
                new CityPickerDialog.onCityPickedListener() {

                    @Override
                    public void onPicked(Province selectProvince,
                                         City selectCity, County selectCounty) {
                        //获取ID selectProvince.getAreaId();

                        s1 = selectProvince != null ? selectProvince
                                .getAreaName() : "";
                        s2 = selectCity != null ? selectCity
                                .getAreaName() : "";
                        s3 = selectCounty != null ? selectCounty
                                .getAreaName() : "";
                        if (s1.equals("北京市")) {
                            if (addressType == 0) {
                                applyLabelHouseholdEd.setText(s1 + s2);
                            } else {
                                applyLabelAddressEd.setText(s1 + s2);
                            }
                        } else {
                            if (addressType == 0) {
                                applyLabelHouseholdEd.setText(s1 + s2 + s3);
                            } else {
                                applyLabelAddressEd.setText(s1 + s2 + s3);
                            }
                        }
                    }
                }).show();
    }

    /**
     * 时间点击事件,打开选择时间控件
     */
    private void openDatePicker() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(ApplyLabelActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int ye, int monthYear, int dayMonth) {
                String dateTime, dateTimeN;
                long tDatetime;
                int month;
                int monthN;
                //当天的零点零分
                Calendar cal = Calendar.getInstance();
                monthN = monthOfYear + 1;
                String strMonthN = monthN < 10 ? "0" + monthN : "" + monthN;
                String dayOfMonthN = dayOfMonth < 10 ? "0" + dayOfMonth : "" + dayOfMonth;
                dateTimeN = year + strMonthN + dayOfMonthN;
                //选择的当天的零点零分
                Calendar c = Calendar.getInstance();
                month = monthYear + 1;
                String strMonth = month < 10 ? "0" + month : "" + month;
                String strDay = dayMonth < 10 ? "0" + dayMonth : "" + dayMonth;
                dateTime = ye + strMonth + strDay;
                Toast.makeText(ApplyLabelActivity.this, "dateTime" + dateTime, Toast.LENGTH_SHORT).show();

                try {
                    c.setTime(new SimpleDateFormat("yyyyMMdd").parse(dateTime));
                    cal.setTime(new SimpleDateFormat("yyyyMMdd").parse(dateTimeN));
                    long ntime = c.getTimeInMillis();
                    tDatetime = cal.getTimeInMillis();
                    monthYear = monthYear + 1;
                    if (ntime <= tDatetime) {
                        applyLabelBuyTimeEd.setText(ye + "年" + monthYear + "月" + dayMonth + "日");
                    } else if (ntime > tDatetime) {
                        Toast.makeText(ApplyLabelActivity.this, "选择日期不能超过当前日期", Toast.LENGTH_SHORT).show();
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }, year, monthOfYear, dayOfMonth);
        datePickerDialog.show();
    }

    private class InitAreaTask extends AsyncTask<Integer, Integer, Boolean> {

        Context mContext;

        Dialog progressDialog;

        public InitAreaTask(Context context) {
            mContext = context;
            progressDialog = Util.createLoadingDialog(mContext, "请稍等...", true,
                    0);
        }

        @Override
        protected void onPreExecute() {

            progressDialog.show();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            progressDialog.dismiss();
            if (provinces.size() > 0) {
                showAddressDialog();
            } else {
                Toast.makeText(mContext, "数据初始化失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected Boolean doInBackground(Integer... params) {
            String address = null;
            InputStream in = null;
            try {
                in = mContext.getResources().getAssets().open("address.txt");
                byte[] arrayOfByte = new byte[in.available()];
                in.read(arrayOfByte);
                address = EncodingUtils.getString(arrayOfByte, "UTF-8");
                JSONArray jsonList = new JSONArray(address);
                Gson gson = new Gson();
                for (int i = 0; i < jsonList.length(); i++) {
                    try {
                        provinces.add(gson.fromJson(jsonList.getString(i),
                                Province.class));

                    } catch (Exception e) {
                    }
                }
                return true;
            } catch (Exception e) {
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {

                    }
                }
            }
            return false;
        }

    }
}
